package com.cms.controller.front;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.cms.Feedback;
import com.cms.entity.Cart;
import com.cms.entity.CartItem;
import com.cms.routes.RouteMapping;
import com.jfinal.plugin.activerecord.Db;

/**
 * Controller - 购物车项
 * 
 * 
 * 
 */
@RouteMapping(url = "/cart_item")
public class CartItemController extends BaseController{

	/**
	 * 更新
	 */
	public void update(){
		if(getCurrentMember()==null){
			renderJson(Feedback.warn("您还没有登录!"));
			return;
		}
	    Cart currentCart = getCurrentCart();
		Long productId = getParaToLong("productId");
		Integer quantity = getParaToInt("quantity");
		CartItem cartItem = new CartItem().dao().find(productId,currentCart.getId());
		if(cartItem == null){
		    cartItem = new CartItem();
		    cartItem.setCartId(currentCart.getId());
	        cartItem.setQuantity(quantity);
	        cartItem.setProductId(productId);
	        if(quantity>0){
	        	cartItem.setIsSelect(true);
	        }else{
	        	cartItem.setIsSelect(false);
	        }
	        cartItem.setCreateDate(new Date());
	        cartItem.setModifyDate(new Date());
	        cartItem.save();
		}else{
            cartItem.setQuantity(quantity);
		    cartItem.update();
		}
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("subtotal", cartItem.getSubtotal());
		result.put("productQuantity", cartItem.getQuantity());
		result.put("quantity", cartItem.getQuantity());
		result.put("totalPrice", currentCart.getTotalPrice());
		result.put("totalQuantity", currentCart.getTotalQuantity());
		result.put("totalWeight", currentCart.getTotalWeight());
		renderJson(Feedback.success(result));
	}
	
	/**
	 * 选择
	 */
	public void choose(){
		String ids = getPara("ids");
		Cart currentCart = getCurrentCart();
		if(StringUtils.isNotBlank(ids)){
			Db.update("update cms_cart_item set isSelect=1 where id in ("+ids+")");
			Db.update("update cms_cart_item set isSelect=0 where id not in ("+ids+")");
		}else{
			Db.update("update cms_cart_item set isSelect=0 where cartId="+currentCart.getId());
		}
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("totalQuantity", currentCart.getTotalQuantity());
		result.put("totalWeight", currentCart.getTotalWeight());
		result.put("totalPrice", currentCart.getTotalPrice());
		renderJson(Feedback.success(result));
	}
	
	
	/**
	 * 删除
	 */
	public void delete(){
		Long id = getParaToLong("id");
		new CartItem().dao().deleteById(id);
		renderJson(Feedback.success(new HashMap<>()));
	}
	
	/**
	 * 清除
	 */
	public void deleteAll(){
		Cart currentCart = getCurrentCart();
		List<CartItem> cartItems = currentCart.getCartItems();
		if(cartItems!=null && cartItems.size()>0){
			for(CartItem cartItem:cartItems){
				cartItem.delete();
			}
		}
		renderJson(Feedback.success(new HashMap<>()));
	}
}
